package com.example.demo.heima.reactor;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname BusTask
 * @description
 * @date 2023/08/12 17:36
 * <p>
 * ******************************************************
 */
public class BusTask implements Runnable {

    private final SocketChannel socketChannel;
    private ByteBuffer buffer;

    public BusTask(ByteBuffer buffer, SocketChannel socketChannel) {
        this.buffer = buffer;
        this.socketChannel = socketChannel;
    }

    @Override
    public void run() {
        // 从buff中拿数据
        buffer.flip(); // 切换读操作
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes); // 该操作是需要读buffer中的数据到bytes
        final String msg = new String(bytes, Charset.defaultCharset());
        System.out.println("从客户端读到数据："+msg);

        // bus


        // 向buff中写数据
        ByteBuffer buffer1 = ByteBuffer.allocate(1024);
        buffer1.put("hello nioclient, i am nioserver".getBytes(StandardCharsets.UTF_8)); // 当前是写buffer
        buffer1.flip(); // 切换读操作
        try {
            socketChannel.write(buffer1); // 该操作是需要读buffer
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
